package com.slf.demo1;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.Collectors;

public class CsvMerger2 {

    // 需要补充的时间点列表（从145715000到145945000）
    private static final String[] SUPPLEMENT_TIMES = {
            "145715000", "145730000", "145745000", "145800000",
            "145815000", "145830000", "145845000", "145900000",
            "145915000", "145930000", "145945000"
    };



//    private static final boolean isMinData = true;
//    private static final  String inputDir = "F:\\股指数据金烨\\106数据min";
//    private static final  String outputDir = "F:\\股指数据金烨\\106数据min提取";

    private static final boolean isMinData = false;
    private static final  String inputDir = "F:\\股指数据金烨\\106数据rec";
    private static final String outputDir = "F:\\股指数据金烨\\106数据rec提取";


    public static void main(String[] args) {



        try {
            List<File> sortedFiles = getSortedFiles(inputDir);

            File outputDirFile = new File(outputDir);
            if (!outputDirFile.exists()) {
                outputDirFile.mkdirs();
            }

            if (sortedFiles.isEmpty()) {
                System.out.println("没有找到符合条件的文件");
                return;
            }

            Map<String, BufferedWriter> writers = new HashMap<>();
            String[] indices = {"000300", "000016", "000852", "000905"};
            for (String index : indices) {
                Path outputPath = Paths.get(outputDir, index + ".csv");
                writers.put(index, Files.newBufferedWriter(outputPath, StandardCharsets.UTF_8));
            }

            for (File file : sortedFiles) {
                processFile(file, writers);
            }

            for (BufferedWriter writer : writers.values()) {
                writer.close();
            }

            System.out.println("处理完成，生成文件: " + String.join(", ", indices) + ".csv");

        } catch (IOException e) {
            System.err.println("处理过程中发生错误: " + e.getMessage());
            e.printStackTrace();
        }
    }

    private static List<File> getSortedFiles(String dirPath) throws IOException {
        File dir = new File(dirPath);
        if (!dir.isDirectory()) {
            throw new IllegalArgumentException("路径不是文件夹: " + dirPath);
        }

        return Arrays.stream(Objects.requireNonNull(dir.listFiles()))
                .filter(file -> file.isFile() && file.getName().startsWith("sifhq") && file.getName().endsWith(".csv"))
                .filter(file -> file.length() > 10240)
                .sorted(Comparator.comparing(file -> file.getName()))
                .collect(Collectors.toList());
    }


    private static void processFile(File file, Map<String, BufferedWriter> writers) throws IOException {
        try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] strs=line.split(",");

                if(strs.length==12){
                    //将该数组的第5、6的字符删除，然后再拼成一个新的字符串覆盖原来的字符串
                    line=strs[0]+","+strs[1]+","+strs[2]+","+strs[3]+","+strs[4]+","+strs[7]+","+strs[8]+","+strs[9]+","+strs[10]+","+strs[11];
                }
                if(line.split(",").length!=10){
                    System.out.println("数据格式错误，程序退出：" + line);
                    return;
                }
                String indexCode = line.substring(0, 6);
                BufferedWriter writer = writers.get(indexCode);

                if (writer == null) {
                    continue;
                }

                // 1. 写入当前行
                writer.write(line);
                writer.newLine();

                // 2. 如果是145700000时刻，补充11条数据
                if (isBaseLine(line)) {
                    String datePart = extractDatePart(line);

                    // 生成并写入11条补充数据
                    for (String newTime : SUPPLEMENT_TIMES) {
                        String newLine = createSupplementLine(line, newTime, datePart);
                        writer.write(newLine);
                        writer.newLine();
                    }
                }
            }
        }
        //System.out.println("已处理文件: " + file.getName());
    }

    private static boolean isBaseLine(String line) {
        int firstComma = line.indexOf(',');
        int secondComma = line.indexOf(',', firstComma + 1);

        if (firstComma == -1 || secondComma == -1) {
            return false;
        }

        String timeField = line.substring(firstComma + 1, secondComma);
        return "145700000".equals(timeField);
    }

    private static String extractDatePart(String line) {
        int lastComma = line.lastIndexOf(',');
        if (lastComma == -1 || lastComma + 1 > line.length()) {
            return "";
        }

        String fullTimestamp = line.substring(lastComma + 1);
        return fullTimestamp.length() >= 8 ? fullTimestamp.substring(0, 8) : "";
    }

    private static String createSupplementLine(String baseLine, String newTime, String datePart) {
        String[] parts = baseLine.split(",");

        if(isMinData){
            return parts[0]+","
                    +newTime+","
                    +parts[2]+","+"0"+","+"0"+","+parts[5]+","+parts[6]+","+parts[7]+","+parts[8]+","
                    +parts[9].substring(0, 8)+newTime;
        }

        return parts[0]+","
                +newTime+","
                +parts[2]+","+parts[3]+","+parts[4]+","+parts[5]+","+parts[6]+","+parts[7]+","+parts[8]+","
                +parts[9].substring(0, 8)+newTime;
    }
}